package com.bigshark.amine_admin.sys.controller;

import com.bigshark.amine_admin.common.annocation.SysLog;
import com.bigshark.amine_admin.common.utils.Constant;
import com.bigshark.amine_admin.sys.model.SysMenu;
import com.bigshark.amine_admin.sys.service.SysMenuService;
import com.bigshark.common.exception.AmineException;
import com.bigshark.common.utills.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {
    @Autowired
    SysMenuService sysMenuService;

    @SysLog("新增菜单")
    @PostMapping("/")
    public R create(@RequestBody SysMenu menu){
        verifyForm(menu);
        sysMenuService.save(menu);
        return R.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenu menu){
        if(StringUtils.isBlank(menu.getName())){
            throw new AmineException("菜单名称不能为空");
        }

        if(menu.getParentId() == null){
            throw new AmineException("上级菜单不能为空");
        }

        //菜单
        if(menu.getType() == Constant.MenuType.MENU.getValue()){
            if(StringUtils.isBlank(menu.getUrl())){
                throw new AmineException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if(menu.getParentId() != 0){
            SysMenu parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if(menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()){
            if(parentType != Constant.MenuType.CATALOG.getValue()){
                throw new AmineException("上级菜单只能为目录类型");
            }
            return ;
        }

        //按钮
        if(menu.getType() == Constant.MenuType.BUTTON.getValue()){
            if(parentType != Constant.MenuType.MENU.getValue()){
                throw new AmineException("上级菜单只能为菜单类型");
            }
            return ;
        }
    }

}
